import 'package:flutter/cupertino.dart';
import 'package:flutter_todolist/db/table/task_table.dart';
import 'package:flutter_todolist/db/table/task_type_table.dart';
import 'package:flutter_todolist/db/table/user_table.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';

class ToDoDB {

  final String dbName = "todo.db";

  factory ToDoDB() => _instance;
  static final ToDoDB _instance = ToDoDB._init();

  ToDoDB._init();

  Database? db;
  final TaskTable taskTable = TaskTable();
  final TaskTypeTable taskTypeTable = TaskTypeTable();
  final UserTable userTable = UserTable();


  initDb() async {
    String databasePath = await getDatabasesPath();

    String path = join(databasePath, dbName);

    debugPrint('数据库路径: $path');

    db = await openDatabase(path, version: 1,
        onCreate: (Database db, int version) async {

          try {
            debugPrint("执行创建表sql语句");

            await db.execute(taskTable.createTable());
            await db.execute(taskTypeTable.createTable());
            await db.execute(userTable.createTable());

          } catch (err) {
            debugPrint("初始化的时候错误error: $err");
            // throw(err);
          }
        });

    taskTable.database = db;
    taskTypeTable.database = db;
    userTable.database = db;

  }

}